package com.shenzhen.horselive.ui.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.JsonObject;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.adapter.PhoneRechargeAdapter;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.base.AppBarActivity;
import com.shenzhen.horselive.beans.CodeBean;
import com.shenzhen.horselive.beans.CommResponseBean;
import com.shenzhen.horselive.beans.MessageEventWXPayresult;
import com.shenzhen.horselive.beans.PayResultBean;
import com.shenzhen.horselive.beans.PayWayBean;
import com.shenzhen.horselive.beans.PhoneRechargeBean;
import com.shenzhen.horselive.beans.PhoneRechargeWXBean;
import com.shenzhen.horselive.beans.RechargeBean;
import com.shenzhen.horselive.beans.UserAcountBean;
import com.shenzhen.horselive.databinding.ActivityPhoneRechargeBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;
import com.shenzhen.horselive.presenter.ViewObserver;
import com.shenzhen.horselive.ui.dialog.InputDialog;
import com.shenzhen.horselive.utils.DecimalUtils;
import com.shenzhen.horselive.utils.DialogManager;
import com.shenzhen.horselive.utils.GetJsonDataUtil;
import com.shenzhen.horselive.utils.PayResult;
import com.shenzhen.horselive.widget.PayViews;
import com.shenzhen.horselive.widget.VerificationCodeInput;
import com.shenzhen.horselive.wx.WXManager;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class PhoneRechargeActivity extends AppBarActivity {

    ActivityPhoneRechargeBinding  binding;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what)
            {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        checkPayResult();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。 showAlert(PayDemoActivity.this, getString(R.string.pay_failed) + payResult);
                        showToast("支付取消");

                    }
                    break;
            }

            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPhoneRechargeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setStyleRed();
        setTitle("充话费");
        //定位
        location();
        initViews();
        initData();
    }


    //定位
    TencentLocationManager  locationManager;
    private  void  location()
    {
        locationManager =  TencentLocationManager.getInstance(this);
        //单点定位
        String[] permissions = {
                Permission.ACCESS_COARSE_LOCATION,
                Permission.ACCESS_FINE_LOCATION,
                Permission.READ_PHONE_STATE,
                Permission.WRITE_EXTERNAL_STORAGE,
        };

        XXPermissions.with(this)
                .permission(permissions)
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean all) {
                        if (all)
                        {

                            TencentLocationRequest request = TencentLocationRequest.create();
                            request.setRequestLevel(3)//包含区域信息
                                    .setAllowGPS(true)
                                    .setIndoorLocationMode(true)
                                    .setInterval(3000)
                            ;
                            int error = locationManager.requestLocationUpdates(request, locationListener, Looper.getMainLooper());
                            if (error == 0)
                                Log.e("addr","注册位置监听器成功！");
                            else
                                Log.e("addr","注册位置监听器失败！");
//                    locationManager.requestSingleFreshLocation(null, locationListener, Looper.getMainLooper());
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {

                    }
                });

    }
    private TencentLocationListener locationListener = new TencentLocationListener() {
        @Override
        public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
            //获取到定位信息
            //没有获取到就算了，不传定位也没关系
            locationManager.removeUpdates(locationListener);
            if(i == TencentLocation.ERROR_OK){
//                locationManager.removeUpdates(locationListener);
                //获取到定位信息
                String  province = tencentLocation.getProvince();
                String  city =  tencentLocation.getCity();
                String  area =  tencentLocation.getDistrict();
                getareaCode(province,city,area);

            }
            else
            {
                showToast("定位失败，请打开GPS");
            }

        }

        @Override
        public void onStatusUpdate(String s, int i, String s1) {

        }
    };

    private String  citycode;
    private String  areacode;
    private void getareaCode(String province, String city, String area) {
        //获取城主的权益
        if (province==null||city==null||area==null)
            return;
        CodeBean codeBean =  GetJsonDataUtil.getInstance().getCode(province, city, area);
        areacode = codeBean.getDistrictCode();
        citycode = codeBean.getCityCode();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEventWXPayresult event) {
        //微信支付的回调
        if (event.getCode()==0)
        {
            checkPayResult();
        }else
        {
            showToast("支付取消");
        }

    };

    /**
     * 话费套餐查询
     */
    private void initData() {
        ApiFactory.getApiService().rechargeList(User.get().getMyInfo().getToken())
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<RechargeBean>(this) {
                    @Override
                    protected void onNextInActive(RechargeBean rechargeBean) {
                        if (rechargeBean.isSuccess())
                        {
                            adapter.setNewInstance(rechargeBean.getData());

                        }else
                        {
                            showToast(rechargeBean.getErrMessage());
                        }
                    }
                });

        //支付渠道
        ApiFactory.getApiService().getPayWaysNormal(User.get().getMyInfo().getToken())
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<PayWayBean>(this) {
                    @Override
                    protected void onNextInActive(PayWayBean payWayBean) {
                        if (payWayBean.isSuccess())
                        {
                            binding.payviews.setList(payWayBean.getData());
                            //获取峰值余额和兑换的比例
                            getAcountForType(1);
                        }
                    }
                });


    }

    //帐户类型: 0:人民币帐户 ,1:蜂值帐户 ,2:红包股帐户 ,3:金卡帐户
    UserAcountBean acountBean;
    private void getAcountForType(int i) {
        ApiFactory.getApiService().accountTypes(User.get().getMyInfo().getToken(),i+"")
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new ViewObserver<UserAcountBean>(this) {
                    @Override
                    protected void onNextInActive(UserAcountBean userAcountBean) {
                      if (userAcountBean.isSuccess())
                      {
                          acountBean = userAcountBean;
                          ratio = userAcountBean.getData().getOneRatio();
                          if (!TextUtils.isEmpty(ratio))
                          {
                              RechargeBean.DataBean dataBean = PhoneRechargeActivity.this.adapter.getItem(0);
                              double  money = Double.parseDouble(dataBean.getCardnum())*Double.parseDouble(dataBean.getFzDiscounts());
                              double takeFenzhi =  money*Double.parseDouble(ratio);
                              binding.tvPayName.setText(String.format("蜂值充值(需支付%s蜂值)",DecimalUtils.keepTenWei(takeFenzhi)));
                          }

                          if (Double.parseDouble(userAcountBean.getData().getValue())==0)
                          {
                              binding.tvFenzhiText.setText("蜂值余额：0.00（不可选）");
                              binding.containerFenzhi.setEnabled(false);
                              isFenZhiPay = false;
                          }
                          else
                          {
                              String value = DecimalUtils.keepTenWei(Double.parseDouble(userAcountBean.getData().getValue()));
                              binding.tvFenzhiText.setText(String.format("蜂值余额：%s",value));
                              binding.containerFenzhi.setEnabled(true);
                              binding.containerFenzhi.performClick();
                          }
                      }
                    }
                });
    }

   PhoneRechargeAdapter  adapter;
   String  ratio;
    private void initViews() {
        binding.tvMyPhone.setText(User.get().getMyInfo().getPhone());
        binding.payviews.setTitleGone();
        adapter = new PhoneRechargeAdapter(R.layout.item_phone_recharge);
        binding.recyclerview.setLayoutManager(new GridLayoutManager(this,3));
        binding.recyclerview.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                PhoneRechargeActivity.this.adapter.setSelectPos(position);
                //更新峰值
                if (!TextUtils.isEmpty(ratio))
                {
                    RechargeBean.DataBean dataBean = PhoneRechargeActivity.this.adapter.getItem(position);
                    double  money = Double.parseDouble(dataBean.getCardnum())*Double.parseDouble(dataBean.getFzDiscounts());
                    double takeFenzhi = money*Double.parseDouble(ratio);
                    binding.tvPayName.setText(String.format("蜂值充值(需支付%s蜂值)",DecimalUtils.keepTenWei(takeFenzhi)));
                }
            }
        });
        binding.btGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });
        binding.containerFenzhi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isFenZhiPay = true;
                binding.imgCheck.setImageResource(R.mipmap.ico_checked);
                //设置选中
                binding.payviews.setNone();
                adapter.setPayType(0);
            }
        });

        binding.payviews.setOnItemClick(new PayViews.OnItemClick() {
            @Override
            public void onclick() {
                isFenZhiPay =false;
                binding.imgCheck.setImageResource(R.mipmap.ico_un_check);
                adapter.setPayType(1);
            }
        });

    }
    boolean  isFenZhiPay =false;
    String  orderrCode;
    String  channelTag;
    //提交
    private void submit() {
//        String  phone = binding.tvPhone.getText().toString();
//        if (TextUtils.isEmpty(phone))
//        {
//            showToast("请填写手机号码");
//            return;
//        }
        if (adapter.getData()==null||adapter.getData().size()==0)
        {
            return;
        }

        String  paytag = null;
        if (isFenZhiPay)
        {
            paytag = "FENGZHI_PAY";
        }
        else
        {
            paytag = binding.payviews.getPayWayItem().getChannelTag();
        }
        channelTag  =paytag;
      String  cardnum =  adapter.getItem(adapter.getSelectPos()).getCardnum();

      if (isFenZhiPay)
      {
          //需要支付的峰值
          double  payFenzhi = Double.parseDouble(adapter.getItem(adapter.getSelectPos()).getCardnum())
                             *Double.parseDouble(adapter.getItem(adapter.getSelectPos()).getFzDiscounts())
                             *Double.parseDouble(acountBean.getData().getOneRatio());

          if (payFenzhi>Double.parseDouble(acountBean.getData().getAmount()))
          {
              showToast("蜂值余额不足，请选择其他支付方式");
              return;
          }
          InputDialog  inputDialog =new InputDialog(this);
          inputDialog.setTextName("支付密码");
          inputDialog.setTextContent("请输入支付密码");
          String finalPaytag = paytag;
          inputDialog.setInputDown(new VerificationCodeInput.Listener() {
              @Override
              public void onComplete(String content) {
                  inputDialog.dismiss();
                  //密码输入完成
                  ApiFactory.getApiService().recharge(User.get().getMyInfo().getToken()
                          ,cardnum,User.get().getMyInfo().getPhone(), finalPaytag,content,areacode,citycode
                  ).compose(SchedulersCompat.applyIoSchedulers())
                          .safeSubscribe(new LoadingViewObserver<PhoneRechargeBean>(PhoneRechargeActivity.this) {
                              @Override
                              protected void onNextInActive(PhoneRechargeBean rechargeBean) {
                                  if (rechargeBean.isSuccess())
                                  {
//                                      orderrCode =rechargeBean.getData().getOrderCode();
                                      showToast("充值成功");
                                      finish();
                                  }else
                                  {
                                      showToast(rechargeBean.getErrMessage());
                                  }

                              }
                          });
              }
          });
          inputDialog.show();
      }
      else
      {     //傻逼后台一下字符串一下对象，，，只能这么愚蠢的写
          String  name =  binding.payviews.getPayWayItem().getChannelName();
          if (name.contains("微信"))
          {
              ApiFactory.getApiService().rechargeWx(User.get().getMyInfo().getToken()
                      ,cardnum,User.get().getMyInfo().getPhone(),paytag,"",areacode,citycode
              ).compose(SchedulersCompat.applyIoSchedulers())
                      .safeSubscribe(new LoadingViewObserver<PhoneRechargeWXBean>(this) {
                          @Override
                          protected void onNextInActive(PhoneRechargeWXBean rechargeBean) {
                              if (rechargeBean.isSuccess())
                              {
                                  orderrCode =rechargeBean.getData().getOrderCode();
                                  if (isFenZhiPay)
                                  {

                                  }else
                                  {
                                      String  name =  binding.payviews.getPayWayItem().getChannelName();
                                      if (name.contains("微信"))
                                      {
                                          WXManager.getInstance().goToPay(rechargeBean.getData().getResult());
                                      }else if (name.contains("支付宝"))
                                      {
                                          Runnable payRunnable = new Runnable() {
                                              @Override
                                              public void run() {
                                                  PayTask alipay = new PayTask(PhoneRechargeActivity.this);
                                                  Map<String,String> result = alipay.payV2(rechargeBean.getData().getResult().toString(),true);
                                                  Message msg = new Message();
                                                  msg.what = SDK_PAY_FLAG;
                                                  msg.obj = result;
                                                  handler.sendMessage(msg);
                                              }
                                          };
                                          // 必须异步调用
                                          Thread payThread = new Thread(payRunnable);
                                          payThread.start();
                                      }

                                  }

                              }else
                              {
                                  showToast(rechargeBean.getErrMessage());
                              }

                          }
                      });

          }
          else if (name.contains("支付宝"))
          {
              ApiFactory.getApiService().recharge(User.get().getMyInfo().getToken()
                      ,cardnum,User.get().getMyInfo().getPhone(),paytag,"",areacode,citycode
              ).compose(SchedulersCompat.applyIoSchedulers())
                      .safeSubscribe(new LoadingViewObserver<PhoneRechargeBean>(this) {
                          @Override
                          protected void onNextInActive(PhoneRechargeBean rechargeBean) {
                              if (rechargeBean.isSuccess())
                              {
                                  orderrCode =rechargeBean.getData().getOrderCode();

                                  if (isFenZhiPay)
                                  {

                                  }else
                                  {
                                      String  name =  binding.payviews.getPayWayItem().getChannelName();
                                      if (name.contains("微信"))
                                      {
                                          JsonObject  jsonObject = (JsonObject) rechargeBean.getData().getResult();
                                          WXManager.getInstance().goToPay(jsonObject.getAsString());
                                      }else if (name.contains("支付宝"))
                                      {
                                          Runnable payRunnable = new Runnable() {
                                              @Override
                                              public void run() {
                                                  PayTask alipay = new PayTask(PhoneRechargeActivity.this);
                                                  Map<String,String> result = alipay.payV2(rechargeBean.getData().getResult().toString(),true);
                                                  Message msg = new Message();
                                                  msg.what = SDK_PAY_FLAG;
                                                  msg.obj = result;
                                                  handler.sendMessage(msg);
                                              }
                                          };
                                          // 必须异步调用
                                          Thread payThread = new Thread(payRunnable);
                                          payThread.start();
                                      }

                                  }

                              }else
                              {
                                  showToast(rechargeBean.getErrMessage());
                              }

                          }
                      });

          }




      }
    }
    //查询支付是否成功
    private void checkPayResult() {
        if (orderrCode==null||channelTag==null)
        {
            return;
        }
        //支付成功
        ApiFactory.getApiService().getPayResult(User.get().getMyInfo().getToken()
                ,orderrCode,channelTag
        ).compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<PayResultBean>(this) {
                    @Override
                    protected void onNextInActive(PayResultBean payResultBean) {
                        if (payResultBean.isSuccess()&&payResultBean.getData().getPayStatus()==1)
                        {
                            showToast("充值成功");
                            finish();
                        }
                        else {
                            showToast(payResultBean.getErrMessage());
                        }
                    }
                });

    }





}